package com.tree;

import java.util.*;

/**
 * 前序遍历
 */
public class PreOrder {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode left = new TreeNode(4);
        TreeNode right = new TreeNode(3);
        TreeNode leaf = new TreeNode(2);

        root.left = left;
        root.right = right;
        left.left = leaf;

        List<Integer> integers = preorderTraversal2(root);
        System.out.println(Arrays.toString(integers.toArray()));
    }
    /**
     * 递归实现
     * @param root
     * @return
     */
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;

        TreeNode left = root.left;
        TreeNode right = root.right;

        result.add(root.val);
        result.addAll(preorderTraversal(left));
        result.addAll(preorderTraversal(right));

        return result;
    }

    /**
     * stack 结构实现
     * @param root
     * @return
     */
    public static List<Integer> preorderTraversal2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;

        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            if (node.right != null){
                stack.add(node.right);
            }
            if (node.left != null){
                stack.add(node.left);
            }
            result.add(node.val);
        }
        return result;
    }
}
